package com.fast.controller;

import java.security.Principal;
import java.util.Date;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.DestinationVariable;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.simp.SimpMessageHeaderAccessor;
import org.springframework.messaging.simp.annotation.SubscribeMapping;
import org.springframework.stereotype.Controller;

import com.fast.common.WebSocketConstant;
import com.fast.modules.acd.entity.Node;
import com.fast.modules.acd.service.QueueService;
import com.fast.modules.websocket.dto.BaseMessage;
import com.fast.modules.websocket.service.UserService;
import com.fast.modules.websocket.service.WebSocketService;

import io.swagger.annotations.ApiOperation;

@Controller
public class WebSocketController {

    @Autowired
    private UserService userService;
    
    @Autowired
    QueueService queueService;

    @Autowired
    private WebSocketService ws;
    
    @Autowired
    Map<String, String> sessionMap;


    @SubscribeMapping("/topic/position/{clientID}")//浏览器发送请求通过@messageMapping 映射/welcome 这个地址。
    public void join(@DestinationVariable String clientID, @Header String skillID, SimpMessageHeaderAccessor header) throws Exception {
    	
    	String sessionID = header.getSessionId();
        
    	Node node = new Node(clientID, skillID);
    	
    	sessionMap.put(sessionID, clientID);
    	
    	int position = queueService.join(node);
    	BaseMessage message = new BaseMessage();
    	message.setContent(position);
    	ws.sentMsg(clientID, WebSocketConstant.CLIENT_TOPIC_NAME, message);
    }


    /**
     * 客户向座席发送
     * @param principal
     * @param message
     */
    @MessageMapping("/toSeat")
    @ApiOperation("客户向座席发送")
    public void toSeat(BaseMessage message){

        if (userService.getOnlineRelation().containsKey(message.getSender())){
            String seatId = userService.getOnlineRelation().get(message.getSender());

            message.setReceiver(seatId);
            message.setDate(new Date());
            ws.sentMsgForUser(message.getReceiver(), "/topic/seat/chat", message);
        }

    }

    /**
     * 座席向客户发送
     * @param principal
     * @param message
     */
    @MessageMapping("/toClient")
    @ApiOperation("座席向客户发送")
    public void toClient(Principal principal, BaseMessage message){
        String seatId = principal.getName();
        if (userService.getOnlineRelation().containsKey(message.getReceiver())){
            //String clientId = userService.getOnlineRelation().con
            message.setSender(seatId);
            ws.sentMsg(message.getReceiver(), "/topic/client/chat", message);
        }

    }
}